#!/usr/local/env python
# -*- coding: utf-8 -*-
import os
import glob


def get_plugins_path(config):
    """
    获取插件路径
    :param config: 配置文件的实例
    :return: 插件路径
    """
    if os.name == "nt":
        return os.path.expandvars(config.get("agent", "plugins"))
    else:
        return config.get("agent", "plugins")


def get_plugin_name(plugin):
    """
    获取插件名称
    :param plugin: 插件路径或插件对象
    :return: 插件名称
    """
    if isinstance(plugin, str):
        basename = os.path.basename(plugin)
        return os.path.splitext(basename)[0]
    else:
        return plugin.__name__


def get_plugins(config, state="enabled"):
    """
    获取插件列表
    :param config: 配置文件的实例
    :param state: 插件状态，"enabled" 或 "disabled"
    :return: 插件列表
    """
    plugins_path = get_plugins_path(config)
    plugins = []
    for filename in glob.glob(os.path.join(plugins_path, "*.py")):
        plugin_name = get_plugin_name(filename)
        if plugin_name == "plugins":
            continue
        config._config_section_create(plugin_name)

        if state == "enabled":
            if config.getboolean(plugin_name, "enabled"):
                plugins.append(plugin_name)
        elif state == "disabled":
            if not config.getboolean(plugin_name, "enabled"):
                plugins.append(plugin_name)
    return plugins
